// 云函数模板
// 部署：在 cloud-functions/login 文件夹右击选择 “上传并部署”

const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})

exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()

  let info = event;
  info.open_id = wxContext.OPENID;

  const db = cloud.database();
  const userinfoCN = db.collection('userinfo')

  let status = {
    isOk: true,
    message: ""
  }
  let res = await userinfoCN.where(info).get();
  // return res;
  if (res.data.length == 0) {
    await userinfoCN.add({
      data: info,
      success: function(res) {
      }
    })
    return {
      isOk: true,
      message: "更新成功"
    }
  } else {
    return {
      isOk: true,
      message: "无需更新"
    }
  }
}